package models

import (
	"bytes"
	"compress/flate"
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/lzqysoft/ims/libs/pythonweed"
	"gitee.com/lzqysoft/ims/libs/weed"
	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"github.com/mholt/archiver"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"reflect"
	"strings"
	"time"

	"gitee.com/lzqysoft/ims/libs"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type ImsProject struct {
	Id                     string                    `orm:"column(id);pk"`
	Type                   int                       `orm:"column(type);null"`
	Seq                    int                       `orm:"column(seq);null"`
	Remark                 string                    `orm:"column(remark);null"`
	Status                 int                       `orm:"column(status);null"`
	Isdelete               int                       `orm:"column(isdelete);null"`
	Ctime                  time.Time                 `orm:"column(ctime);type(timestamp with time zone);null"`
	Creater                string                    `orm:"column(creater);null"`
	CId                    string                    `orm:"column(c_id);null"`
	Utime                  time.Time                 `orm:"column(utime);type(timestamp with time zone);null"`
	Updater                string                    `orm:"column(updater);null"`
	UId                    string                    `orm:"column(u_id);null"`
	OrgId                  string                    `orm:"column(org_id);null"`
	DeptId                 string                    `orm:"column(dept_id);null"`
	SequenceId             string                    `orm:"column(sequence_id);null"`
	Name                   string                    `orm:"column(name);null"`
	Level                  int                       `orm:"column(level);null"`
	Source                 int                       `orm:"column(source);null"`
	Character              int                       `orm:"column(character);null"`
	SubjectId              string                    `orm:"column(subject_id);null"`
	SubjectName            string                    `orm:"column(subject_name);null"`
	Start                  time.Time                 `orm:"column(start);type(timestamp with time zone);null"`
	End                    time.Time                 `orm:"column(end);type(timestamp with time zone);null"`
	TutorId                string                    `orm:"column(tutor_id);null"`
	TutorName              string                    `orm:"column(tutor_name);null"`
	WordUrl                string                    `orm:"column(word_url);null"`
	Md5                    string                    `orm:"column(md5);null"`
	Content                string                    `orm:"column(content);null"`
	Schedule               string                    `orm:"column(schedule);null"`
	Scheme                 string                    `orm:"column(scheme);null"`
	Budget                 float64                   `orm:"column(budget);null"`
	Used                   float64                   `orm:"column(used);null"`
	ProfessorGroupId       string                    `orm:"column(professor_group_id);null"`
	DeptName               string                    `orm:"column(dept_name);null"`
	Desc                   string                    `orm:"column(desc);null"`
	Reason                 string                    `orm:"column(reason);null"`
	SheduleTable           string                    `orm:"column(shedule_table);null"`
	Expect                 string                    `orm:"column(expect);null"`
	GroupDetail            string                    `orm:"column(groupdetail);null"`
	Analysis               string                    `orm:"column(analysis);null"`
	Benefit                string                    `orm:"column(benefit);null"`
	TutorDetail            string                    `orm:"column(tutor_detail);null"`
	Place                  string                    `orm:"column(place);null"`
	Step                   int                       `orm:"column(step);null"`
	No                     string                    `orm:"column(no);null"`
	ProvinceNo             string                    `orm:"column(province_no);null"`
	ProjectType            int                       `orm:"column(project_type);null"`
	ImsBudget              []*ImsBudget              `orm:"reverse(many)"` // fk 的反向关系
	ImsProjectGroup        []*ImsProjectGroup        `orm:"reverse(many)"` // fk 的反向关系
	ImsProjectAttachment   []*ImsProjectAttachment   `orm:"reverse(many)"` // fk 的反向关系
	ImsProjectMediumTerm   []*ImsProjectMediumTerm   `orm:"reverse(many)"`
	ImsProjectFinishReport []*ImsProjectFinishReport `orm:"reverse(many)"`
	ImsTotur               []*ImsTotur               `orm:"reverse(many)"`
	Score1                 int                       `orm:"column(score1);null"`
	Score2                 int                       `orm:"column(score2);null"`
	Score3                 int                       `orm:"column(score3);null"`
}

type Shedule struct {
	Shedule int `json:"shedule"`
	Result  int `json:"result"`
}

func (t *ImsProject) TableName() string {
	return "ims_project"
}

// 设置当前进度
func (t *ImsProject) SetCurrentStatus(shedule, result int) {
	s := &Shedule{shedule, result}
	b, _ := json.Marshal(s)
	t.Schedule = string(b)
}

// 获取进度字符串
func (t *ImsProject) GetCurrentStatus() string {
	jsonstr := t.Schedule
	s := &Shedule{}
	//stateStr :=  make([]string, 0)
	if err := json.Unmarshal([]byte(jsonstr), s); err != nil {
		return ""
	}
	switch s.Shedule {
	case 0:
		return "立项" + getSheduleStrByType(s.Result)
	case 1:
		return "中期检查" + getSheduleStrByType(s.Result)
	case 2:
		return "项目结题" + getSheduleStrByType(s.Result)
	default:
		return ""
	}
}
func getSheduleStrByType(result int) string {
	switch result {
	case 0:
		return "未通过"
	case 1:
		return "已通过"
	case 2:
		return "审核中"
	default:
		return "其它"
	}
}
func init() {
	orm.RegisterModel(new(ImsProject))
}
func NewImsProject() *ImsProject {
	return &ImsProject{
		Id:       libs.UUID(),
		Status:   1,
		Isdelete: 0,
		Utime:    time.Now(),
		Ctime:    time.Now(),
	}
}

// AddImsProject insert a new ImsProject into database and returns
// last inserted Id on success.
func AddImsProject(m *ImsProject) (id int64, err error) {
	o := orm.NewOrm()

	o.Begin()

	if id, err = o.Insert(m); err != nil {
		beego.Debug(err)
		o.Rollback()
		return
	}
	if len(m.ImsBudget) > 0 {
		for _, v := range m.ImsBudget {
			v.ImsProject = m
			if _, err = o.Insert(v); err != nil {
				beego.Debug(err)
				o.Rollback()
				return 0, err
			}
		}
	}
	if len(m.ImsTotur) > 0 {
		for _, v := range m.ImsTotur {
			v.ImsProject = m
			if _, err = o.Insert(v); err != nil {
				beego.Debug(err)
				o.Rollback()
				return 0, err
			}
		}
	}
	if len(m.ImsProjectGroup) > 0 {
		for _, v := range m.ImsProjectGroup {
			v.ImsProject = m
			if _, err = o.Insert(v); err != nil {
				beego.Debug(err)
				o.Rollback()
				return 0, err
			}
		}
	}

	if len(m.ImsProjectAttachment) > 0 {
		for _, v := range m.ImsProjectAttachment {
			v.ImsProject = m
			if _, err = o.Insert(v); err != nil {
				beego.Debug(err)
				o.Rollback()
				return 0, err
			}
		}
	}

	//id, err = o.Insert(m)
	err = o.Commit()
	switch m.ProjectType {
	case 0:
		res, err := pythonweed.GenerateSetUp(m)
		if err != nil {
			beego.Debug(err)
			return 0, err
		}
		if res.Status == 0 {
			beego.Debug("generate docx failed!", res.Msg)
			return 0, err
		}
		v, err := GetImsProjectById(m.Id)
		v.WordUrl = res.Fid
		UpdateImsProjectById(v)
	case 1:
		res, err := pythonweed.GenerateSetUp2(m)
		if err != nil {
			beego.Debug(err)
			return 0, err
		}
		if res.Status == 0 {
			beego.Debug("generate docx failed!", res.Msg)
			return 0, err
		}
		v, err := GetImsProjectById(m.Id)
		v.WordUrl = res.Fid
		UpdateImsProjectById(v)
	case 2:
		res, err := pythonweed.GenerateSetUp3(m)
		if err != nil {
			beego.Debug(err)
			return 0, err
		}
		if res.Status == 0 {
			beego.Debug("generate docx failed!", res.Msg)
			return 0, err
		}
		v, err := GetImsProjectById(m.Id)
		v.WordUrl = res.Fid
		UpdateImsProjectById(v)
	default:

	}
	//if m.ProjectType == 0 {
	//	res, err := pythonweed.GenerateSetUp(m)
	//	if err != nil {
	//		beego.Debug(err)
	//		return 0, err
	//	}
	//	if res.Status == 0 {
	//		beego.Debug("generate docx failed!", res.Msg)
	//		return 0, err
	//	}
	//	v, err := GetImsProjectById(m.Id)
	//	v.WordUrl = res.Fid
	//	UpdateImsProjectById(v)
	//}
	return
}

// GetImsProjectById retrieves ImsProject by Id. Returns error if
// Id doesn't exist
func GetImsProjectById(id string) (v *ImsProject, err error) {
	o := orm.NewOrm()
	v = &ImsProject{Id: id}
	if err = o.Read(v); err != nil {
		beego.Debug(err)
		return nil, err
	}
	//v = &ImsProject{Id: id}
	//if err = o.Read(v); err == nil {
	//	return v, nil
	//}
	if _, err = o.LoadRelated(v, "ImsBudget", 1); err != nil {
		beego.Debug(err)
		return v, err
	}
	// beego orm
	// https://github.com/astaxie/beego/blob/7452151beec2f43c42122fd91b7523bcbccf05be/orm/orm.go#L273
	// for i, arg := range args {
	//		switch i {
	//		case 0:
	//			if v, ok := arg.(bool); ok {
	//				if v {
	//					relDepth = DefaultRelsDepth
	//				}
	//			} else if v, ok := arg.(int); ok {
	//				relDepth = v
	//			}
	//		case 1:
	//			limit = ToInt64(arg)
	//		case 2:
	//			offset = ToInt64(arg)
	//		case 3:
	//			order, _ = arg.(string)
	//		}
	//	}

	if _, err = o.LoadRelated(v, "ImsProjectGroup", false, 1, -1, 0, "Seq"); err != nil {
		beego.Debug(err)
		return v, err
	}
	if _, err = o.LoadRelated(v, "ImsProjectAttachment", 1); err != nil {
		beego.Debug(err)
		return v, err
	}
	if _, err = o.LoadRelated(v, "ImsProjectFinishReport", 1); err != nil {
		beego.Debug(err)
		return v, err
	}
	if _, err = o.LoadRelated(v, "ImsProjectMediumTerm", 1); err != nil {
		beego.Debug(err)
		return v, err
	}
	if _, err = o.LoadRelated(v, "ImsTotur"); err != nil {
		beego.Debug(err)
		return v, err
	}

	return v, nil
}

// GetImsProjectByIdNoRel retrieves ImsProject by Id. Returns error if
// Id doesn't exist. it only related a bit relations
func GetImsProjectByIdNoRel(id string) (v *ImsProject, err error) {
	o := orm.NewOrm()
	v = &ImsProject{Id: id}
	if err = o.Read(v); err != nil {
		beego.Debug(err)
		return nil, err
	}
	//v = &ImsProject{Id: id}
	//if err = o.Read(v); err == nil {
	//	return v, nil
	//}
	if _, err = o.LoadRelated(v, "ImsBudget", 1); err != nil {
		beego.Debug(err)
		return v, err
	}
	// beego orm
	// https://github.com/astaxie/beego/blob/7452151beec2f43c42122fd91b7523bcbccf05be/orm/orm.go#L273
	// for i, arg := range args {
	//		switch i {
	//		case 0:
	//			if v, ok := arg.(bool); ok {
	//				if v {
	//					relDepth = DefaultRelsDepth
	//				}
	//			} else if v, ok := arg.(int); ok {
	//				relDepth = v
	//			}
	//		case 1:
	//			limit = ToInt64(arg)
	//		case 2:
	//			offset = ToInt64(arg)
	//		case 3:
	//			order, _ = arg.(string)
	//		}
	//	}

	if _, err = o.LoadRelated(v, "ImsProjectGroup", false, 1, -1, 0, "Seq"); err != nil {
		beego.Debug(err)
		return v, err
	}
	if _, err = o.LoadRelated(v, "ImsProjectAttachment", 1); err != nil {
		beego.Debug(err)
		return v, err
	}
	//if _, err = o.LoadRelated(v, "ImsProjectFinishReport", 1); err != nil {
	//	beego.Debug(err)
	//	return v, err
	//}
	//if _, err = o.LoadRelated(v, "ImsProjectMediumTerm",1); err != nil {
	//	beego.Debug(err)
	//	return v, err
	//}
	if _, err = o.LoadRelated(v, "ImsTotur"); err != nil {
		beego.Debug(err)
		return v, err
	}

	return v, nil
}

func GetImsProjectByMediumTermId(id string) (v *ImsProject, err error) {
	m, _ := GetImsProjectMediumTermById(id)
	v, err = GetImsProjectById(m.ImsProject.Id)
	return v, err
}
func GetImsProjectByFinishReportId(id string) (v *ImsProject, err error) {
	m, _ := GetImsProjectFinishReportById(id)
	v, err = GetImsProjectById(m.ImsProject.Id)
	return v, err
}

// GetAllImsProject retrieves all ImsProject matches certain condition. Returns empty list if
// no records exist
func GetAllImsProject(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(ImsProject))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []ImsProject
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateImsProject updates ImsProject by Id and returns error if
// the record to be updated doesn't exist
func UpdateImsProjectById(m *ImsProject) (err error) {
	o := orm.NewOrm()
	v := ImsProject{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)

		}
	}
	return
}

func UpdateImsProjectRel(m *ImsProject) (err error) {
	o := orm.NewOrm()
	o.Begin()
	v := ImsProject{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err != nil {
		beego.Debug(err)
		o.Rollback()
		return err
	}
	//ImsBudget              []*ImsBudget              `orm:"reverse(many)"` // fk 的反向关系
	//ImsProjectGroup        []*ImsProjectGroup        `orm:"reverse(many)"` // fk 的反向关系
	//ImsProjectAttachment   []*ImsProjectAttachment   `orm:"reverse(many)"` // fk 的反向关系
	//ImsProjectMediumTerm   []*ImsProjectMediumTerm   `orm:"reverse(many)"`
	//ImsProjectFinishReport []*ImsProjectFinishReport `orm:"reverse(many)"`
	//ImsTotur               []*ImsTotur               `orm:"reverse(many)"`
	if _, err = o.LoadRelated(&v, "ImsBudget"); err != nil {
		beego.Debug(err)
		o.Rollback()
		return err
	}
	//o.QueryM2M(new(ImsProject), "ims_project").Add()
	if _, err = o.QueryTable(new(ImsBudget)).Filter("project_id", v.Id).Delete(); err != nil {
		beego.Debug(err)
		o.Rollback()
		return err
	}
	for _, v := range m.ImsBudget {
		v.ImsProject = m
		if _, err = o.Insert(v); err != nil {
			beego.Debug(err)
			o.Rollback()
			return err
		}
	}
	if _, err := o.Update(m); err != nil {
		beego.Debug(err)
		o.Rollback()
		return err
	}

	return o.Commit()
}

// DeleteImsProject deletes ImsProject by Id and returns error if
// the record to be deleted doesn't exist
func DeleteImsProject(id string) (err error) {
	o := orm.NewOrm()
	v := ImsProject{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&ImsProject{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

func GetImsProjectByOrg(orgId string) ([]ImsProject, error) {
	o := orm.NewOrm()
	var l []ImsProject
	_, err := o.QueryTable(new(ImsProject)).Filter("Isdelete", 0).Filter("Status", 1).Filter("OrgId", orgId).
		OrderBy("-Ctime").All(&l, "Id", "Ctime", "Creater", "Cid", "Name", "Level", "Source", "Start", "End",
		"TutorId", "TutorName", "Budget", "Type")
	return l, err
}

func GetImsProjectByDept(deptId string) ([]ImsProject, error) {
	o := orm.NewOrm()
	var l []ImsProject
	_, err := o.QueryTable(new(ImsProject)).Filter("Isdelete", 0).Filter("Status", 1).Filter("DeptId", deptId).
		OrderBy("-Ctime").All(&l, "Id", "Ctime", "Creater", "Cid", "Name", "Level", "Source", "Start", "End",
		"TutorId", "TutorName", "Budget", "Type")
	return l, err
}

func GetImsProjectByUser(userId string) ([]ImsProject, error) {
	o := orm.NewOrm()
	var l []ImsProject
	_, err := o.QueryTable(new(ImsProject)).Filter("Isdelete", 0).Filter("Status", 1).Filter("UId", userId).
		OrderBy("-Ctime").All(&l, "Id", "Ctime", "Creater", "Cid", "Name", "Level", "Source", "Start", "End",
		"TutorId", "TutorName", "Budget", "Type")
	return l, err
}

func GetImsProjectsByRoleType(user *User) ([]ImsProject, error) {
	role := user.Role[0]
	beego.Debug("ROLE_TYPE", role.Type)
	switch role.Type {
	case 0:
		//return make([]ImsProject,0), nil
		return getAllImsProject()
	case 1:
		//return make([]ImsProject,0), nil
		return getAllImsProject()
	case 2:
		return GetImsProjectByOrg(user.Organization.Id)
	case 3:
		return GetImsProjectByDept(user.Dept[0].Id)
	case 4:
		return GetImsProjectByUser(user.Id)
	default:
		return make([]ImsProject, 0), nil
	}
}

// 获取所有
func getAllImsProject() ([]ImsProject, error) {
	o := orm.NewOrm()
	var l []ImsProject
	_, err := o.QueryTable(new(ImsProject)).Filter("Isdelete", 0).Filter("Status", 1).
		OrderBy("-Ctime").All(&l, "Id", "Ctime", "Creater", "Cid", "Name", "Level", "Source", "Start", "End",
		"TutorId", "TutorName")
	return l, err
}

func SoftDeleteImsProject(l []ImsProject, user *User) error {
	if len(l) == 0 {
		return nil
	}
	o := orm.NewOrm()
	o.Begin()
	var ids []string
	for _, v := range l {
		ids = append(ids, v.Id)
	}
	if _, err := o.QueryTable(new(ImsProject)).Filter("Id__in", ids).Update(orm.Params{
		"Status":   0,
		"Isdelete": 1,
		"Utime":    time.Now(),
		"UId":      user.Id,
		"Updater":  user.Abbr,
	}); err != nil {
		o.Rollback()
		return err
	}
	return o.Commit()
}

// 流程开始
// 0 立项申报， 1 中期检查， 2 结题 ， 3 项目变更
func StartImsProjectFlow(l ImsProject, flowType int, user *User) error {
	// o := orm.NewOrm()
	switch flowType {
	case 0:
		return projectApprovalFlowStart(l, user)
	case 1:
		return projectCheckFlowStart(l, user)
	case 2:
		return projectFinsishFlowStart(l, user)
	case 3:
		return projectChangeFlowStart(l, user)
	default:
		return errors.New("error flowType value, flowType should in 0,1,2,3")
	}
}

// projectApprovalFlowStart 开启立项流程
func projectApprovalFlowStart(l ImsProject, user *User) error {
	//sum, err := CheckImsProjectFlowCountByImsProjectIdAndType(l.Id, 0)
	////beego.Debug("CHECK ERROR:" , err)
	//if sum != 0 {
	//	return errors.New("repeat approved !")
	//}
	flow, err := getFlowByType(0)
	if err != nil {
		return err
	}
	//project, err := GetImsProjectById(l.Id)
	//if err != nil {
	//	return err
	//}
	//pf, err := AutoGenerateImsProjectFlowByImsProject(user, project)
	//if err != nil {
	//	return err
	//}
	//v := ImsProjectFlow{}

	// type++
	//l.Type++
	//l.Updater, l.Utime = user.Abbr, time.Now()
	//if _, err := orm.NewOrm().Update(&l); err != nil {
	//	beego.Debug(err)
	//	return  err
	//}
	if _, err := orm.NewOrm().QueryTable(new(ImsProject)).Filter("Id", l.Id).Update(orm.Params{
		"Type":    orm.ColValue(orm.ColAdd, 1),
		"Updater": user.Abbr,
		"Utime":   time.Now(),
	}); err != nil {
		beego.Debug(err)
		return err
	}
	fs, err := InitializationFsm(user, flow.Id, l.TableName(), l.Id)
	if err != nil {
		beego.Debug(err)
		return err
	}
	machine := GetFsmStateMachine(fs)
	ev, _ := GetEventByName("上报")
	args := make(map[string]interface{})
	args[FLOWINSTANCE] = fs
	args[USER] = user
	args[OPTION] = "上报"
	args[REMAEK] = "上报"
	args[RESULT] = 1
	beego.Debug(ev)
	err = machine.Trigger(fs.Currentstate, ev.Id, args)
	//err = SetBusyStart(fs.Busyid, fs.Busyname)
	if err != nil {
		beego.Error("trigger1 err: ", err)
		return err
	}
	return nil
}

// projectCheckFlowStart 开启中期检查流程
func projectCheckFlowStart(l ImsProject, user *User) error {
	//sum, err := CheckImsProjectFlowCountByImsProjectIdAndType(l.Id, 1)
	////beego.Debug("CHECK ERROR:" , err)
	//if sum != 0 {
	//	return errors.New("repeat approved !")
	//}
	flow, err := getFlowByType(1)
	if err != nil {
		return err
	}

	if _, err := orm.NewOrm().QueryTable(new(ImsProject)).Filter("Id", l.Id).Update(orm.Params{
		"Type":    orm.ColValue(orm.ColAdd, 1),
		"Updater": user.Abbr,
		"Utime":   time.Now(),
	}); err != nil {
		beego.Debug(err)
		return err
	}
	fs, err := InitializationFsm(user, flow.Id, l.ImsProjectMediumTerm[0].TableName(), l.ImsProjectMediumTerm[0].Id)
	if err != nil {
		beego.Debug(err)
		return err
	}
	machine := GetFsmStateMachine(fs)
	ev, _ := GetEventByName("上报")
	args := make(map[string]interface{})
	args[FLOWINSTANCE] = fs
	args[USER] = user
	args[OPTION] = "上报"
	args[REMAEK] = "上报"
	args[RESULT] = 1
	err = machine.Trigger(fs.Currentstate, ev.Id, args)
	err = SetBusyStart(fs.Busyid, fs.Busyname)
	if err != nil {
		beego.Error("trigger1 err: ", err)
		return err
	}
	return nil
}

// projectCheckFlowStart 开启结项检查流程
func projectFinsishFlowStart(l ImsProject, user *User) error {
	//sum, err := CheckImsProjectFlowCountByImsProjectIdAndType(l.Id, 2)
	////beego.Debug("CHECK ERROR:" , err)
	//if sum != 0 {
	//	return errors.New("repeat approved !")
	//}
	flow, err := getFlowByType(2)
	if err != nil {
		return err
	}
	//project, err := GetImsProjectById(l.Id)
	//if err != nil {
	//	return err
	//}
	//pf, err := AutoGenerateImsProjectFlowByImsProject2(user, project)
	//if err != nil {
	//	return err
	//}
	//v := ImsProjectFlow{}
	//l.Type++
	//l.Updater, l.Utime = user.Abbr, time.Now()
	//if _, err := orm.NewOrm().Update(&l); err != nil {
	//	beego.Debug(err)
	//	return  err
	//}
	if _, err := orm.NewOrm().QueryTable(new(ImsProject)).Filter("Id", l.Id).Update(orm.Params{
		"Type":    orm.ColValue(orm.ColAdd, 1),
		"Updater": user.Abbr,
		"Utime":   time.Now(),
	}); err != nil {
		beego.Debug(err)
		return err
	}
	fs, err := InitializationFsm(user, flow.Id, l.ImsProjectFinishReport[0].TableName(), l.ImsProjectFinishReport[0].Id)
	if err != nil {
		beego.Debug(err)
		return err
	}
	machine := GetFsmStateMachine(fs)
	ev, _ := GetEventByName("上报")
	args := make(map[string]interface{})
	args[FLOWINSTANCE] = fs
	args[USER] = user
	args[OPTION] = "上报"
	args[REMAEK] = "上报"
	args[RESULT] = 1
	err = machine.Trigger(fs.Currentstate, ev.Id, args)
	err = SetBusyStart(fs.Busyid, fs.Busyname)
	if err != nil {
		beego.Error("trigger1 err: ", err)
		return err
	}
	return nil
}

// projectChangeFlowStart 开启项目变更流程
func projectChangeFlowStart(l ImsProject, user *User) error {
	//sum, err := CheckImsProjectFlowCountByImsProjectIdAndType(l.Id, 3)
	////beego.Debug("CHECK ERROR:" , err)
	//if sum != 0 {
	//	return errors.New("repeat approved !")
	//}
	flow, err := getFlowByType(3)
	if err != nil {
		return err
	}
	//project, err := GetImsProjectById(l.Id)
	//if err != nil {
	//	return err
	//}

	//pf, err := AutoGenerateImsProjectFlowByImsProject3(user, &l)
	//if err != nil {
	//	return err
	//}
	v := ImsProjectFlow{}
	fs, err := InitializationFsm(user, flow.Id, v.TableName(), l.Id)
	if err != nil {
		beego.Debug(err)
		return err
	}
	machine := GetFsmStateMachine(fs)
	ev, _ := GetEventByName("上报")
	args := make(map[string]interface{})
	args[FLOWINSTANCE] = fs
	args[USER] = user
	args[OPTION] = "上报"
	args[REMAEK] = "上报"
	args[RESULT] = 1
	err = machine.Trigger(fs.Currentstate, ev.Id, args)
	err = SetBusyStart(fs.Busyid, fs.Busyname)
	if err != nil {
		beego.Error("trigger1 err: ", err)
		return err
	}
	return nil
}

//
func getFlowByType(ftype int) (*Flow, error) {
	var flow Flow
	approveId := beego.AppConfig.String("ftype_id_0")
	checkId := beego.AppConfig.String("ftype_id_1")
	finishId := beego.AppConfig.String("ftype_id_2")
	changeId := beego.AppConfig.String("ftype_id_3")
	beego.Debug("ftype", ftype)
	beego.Debug("approveId", approveId)
	o := orm.NewOrm()
	qs := o.QueryTable(new(Flow)).Filter("Isdelete", 0).Filter("Status", 1)
	switch ftype {
	case 0:
		qs = qs.Filter("Id", approveId)
	case 1:
		qs = qs.Filter("Id", checkId)
	case 2:
		qs = qs.Filter("Id", finishId)
	case 3:
		qs = qs.Filter("Id", changeId)
	default:
	}
	if err := qs.One(&flow); err != nil {
		beego.Debug(err)
		return nil, err
	}
	return &flow, nil
}

// QueryLegalProject
// 根据用户查询合法的项目
// 包括已立项，中期检查中，中期检查结束，结项中， 结题等，
func QueryLegalProject(user *User) ([]orm.Params, error) {
	o := orm.NewOrm()
	var ps []orm.Params

	if _, err := o.QueryTable(new(ImsProject)).Filter("Isdelete", 0).Values(&ps); err != nil {
		beego.Debug(err)
		return nil, err
	}
	var pf []orm.Params
	if _, err := o.QueryTable(new(ImsProjectFlow)).Filter("Isdelete", 0).Filter("Type__lt", 4).
		OrderBy("Ctime").Values(&pf); err != nil {
		beego.Debug(err)
		return nil, err
	}
	res := make([]orm.Params, 0)
	for _, v := range ps {
		flag := false
		str := make([]string, 0)
		for _, f := range pf {
			flag = true
			if f["ProjectId"].(string) == v["Id"].(string) {
				switch {
				case f["Type"].(int64) == 0:
					if f["Status"].(int64) == 2 {
						str = append(str, "立项审核中")
					} else {
						if f["Result"] == 1 {
							str = append(str, "已立项")
						} else {
							str = append(str, "立项审核未通过")
						}
					}
				case f["Type"].(int64) == 1:
					if f["Status"].(int64) == 2 {
						str = append(str, "中期检查中")
					} else {
						if f["Result"] == 1 {
							str = append(str, "已通过中期检查")
						} else {
							str = append(str, "未通过中期检查")
						}
					}
				case f["Type"].(int64) == 2:
					if f["Status"].(int64) == 2 {
						str = append(str, "项目结题审核中")
					} else {
						if f["Result"] == 1 {
							str = append(str, "项目已结题")
						} else {
							str = append(str, "未通过项目结题审核")
						}
					}
				}
			}
		}
		beego.Debug(str)
		v["Status"] = strings.Join(str, ",")
		if flag {
			res = append(res, v)
		}
	}
	return res, nil
}

func GetImsProjectByType(ptype int) ([]ImsProject, error) {
	o := orm.NewOrm()
	var l []ImsProject
	if _, err := o.QueryTable(new(ImsProject)).Filter("Isdelete", 0).Filter("Status", ptype).All(&l,
		"Id", "Type", "Seq", "Remark", "Status", "Isdelete", "Ctime", "Creater", "Utime", "Updater", "Name", "Level",
		"Source", "Character", "SubjectName", "Start", "End", "TutorName", "Budget", "Used"); err != nil {
		beego.Debug(err)
		return nil, err
	}
	return l, nil
}

func GetImsProjectByTypeUserAndRole(ptype, status int, user *User) ([]ImsProject, error) {
	o := orm.NewOrm()
	var l []ImsProject
	//m := &ImsProject{}
	qs := o.QueryTable(new(ImsProject)).Filter("Isdelete", 0).Filter("Type", ptype).Filter("Status", status)
	switch user.Role[0].Type {
	case 0:
		// 超管，查询全部
	case 1:
		// 超管，查询全部
	case 2:
		// 组织级，根据org查询
		qs = qs.Filter("OrgId", user.Organization.Id)
	case 3:
		// 部门级
		qs = qs.Filter("DeptId", user.Dept[0].Id)
	case 4:
		qs = qs.Filter("CId", user.Id)
	default:

	}
	if _, err := qs.All(&l); err != nil {
		beego.Debug(err)
		return nil, err
	}
	return l, nil
}

func QueryLegeProject(user *User, sequenceId string) ([]orm.Params, error) {
	o := orm.NewOrm()
	var l []orm.Params
	//m := &ImsProject{}
	qs := o.QueryTable(new(ImsProject)).Filter("Isdelete", 0).Filter("Type__gte", 1).Filter("Type__lt", 99).Filter("SequenceId", sequenceId)
	switch user.Role[0].Type {
	case 0:
		// 超管，查询全部
	case 1:
		// 超管，查询全部
	case 2:
		// 组织级，根据org查询
		qs = qs.Filter("OrgId", user.Organization.Id)
	case 3:
		// 部门级
		qs = qs.Filter("DeptId", user.Dept[0].Id)
	case 4:
		qs = qs.Filter("CId", user.Id)
	default:

	}
	if _, err := qs.Values(&l); err != nil {
		beego.Debug(err)
		return nil, err
	}
	for _, v := range l {
		itype := v["Type"].(int64)
		v["Type"] = libs.GetProjectType(int(itype))
	}
	return l, nil
}

func GetImsProjectBySequenceAndUser(sequenceId string, user *User) ([]ImsProject, error) {
	o := orm.NewOrm()
	var l []ImsProject
	//var m ImsProject
	qs := o.QueryTable(new(ImsProject)).Filter("Isdelete", 0).Filter("Type__lt", 1).Filter("SequenceId", sequenceId).OrderBy("-Ctime")
	switch user.Role[0].Type {
	case 0:
		// 超管，查询全部
	case 1:
		// 超管，查询全部
	case 2:
		// 组织级，根据org查询
		qs = qs.Filter("OrgId", user.Organization.Id)
	case 3:
		// 部门级
		qs = qs.Filter("DeptId", user.Dept[0].Id)
	case 4:
		qs = qs.Filter("CId", user.Id)
	default:

	}
	if _, err := qs.RelatedSel().All(&l); err != nil {
		beego.Debug(err)
		return nil, err
	}

	return l, nil
}

// UpdateImsPorjectUsed 修改已使用预算
func UpdateImsPorjectUsed(o orm.Ormer, id string) error {
	project := &ImsProject{Id: id}
	if err := o.Read(project); err != nil {
		return err
	}
	project.Budget, project.Used = 0, 0
	var budget []ImsBudget
	if _, err := o.QueryTable(new(ImsBudget)).Filter("project_id", id).Filter("Isdelete", 0).All(&budget); err != nil {
		beego.Debug(err)
		return err
	} else {
		for _, v := range budget {
			project.Budget += v.Budget
		}
		if _, err := o.Update(project); err != nil {
			return err
		}
	}
	var useds []ImsUsed
	if _, err := o.QueryTable(new(ImsUsed)).Filter("ProjectId", id).Filter("Isdelete", 0).All(&useds); err != nil {
		return err
	} else {
		for _, v := range useds {
			project.Used += v.Used
		}
		if project.Used > project.Budget {
			return errors.New("error budget and used!")
		}
		if _, err := o.Update(project); err != nil {
			return err
		} else {
			return nil
		}
	}
}

// GenerateZip generate project archive package
// DONE
func generateZip(project *ImsProject) (fid string, err error) {
	// 1. query project
	//_, err = GetImsProjectById(id)
	//project, err := GetImsProjectById(id)
	//if err != nil {
	//	beego.Debug(err)
	//	return "", err
	//}
	// 2. mkdir
	dir, err := makeTmpDir()
	if err != nil {
		beego.Debug(err)
		return "", err
	}
	defer os.RemoveAll(dir)

	// 3. download project document
	// 3.1 申报书与附件
	base := "http://" + beego.AppConfig.String("weed_volume")
	{
		setupDir := filepath.Join(dir, "申报书")
		err = os.MkdirAll(setupDir, 0777)
		if err != nil {
			beego.Debug(err)
			return "", err
		}
		err = downloadFile(base+"/"+project.WordUrl, filepath.Join(setupDir, "申报书.docx"))
		if err != nil {
			beego.Debug(err)
			return "", err
		}
		for _, v := range project.ImsProjectAttachment {
			filename := filepath.Join(setupDir, v.Name)
			err = downloadFile(base+"/"+v.Url, filename)
			if err != nil {
				beego.Debug(err)
				return "", err
			}
		}
	}
	// 3.2 中期检查与附件
	if len(project.ImsProjectMediumTerm) > 0 {
		mediumDir := filepath.Join(dir, "中期检查表")
		err = os.MkdirAll(mediumDir, 0777)
		if err != nil {
			beego.Debug(err)
			return "", err
		}
		medium := project.ImsProjectMediumTerm[0]
		err = downloadFile(base+"/"+medium.WordUrl, filepath.Join(mediumDir, "中期检查表.docx"))
		if err != nil {
			beego.Debug(err)
			return "", err
		}
		//for _, v := range medium.ImsProjectAttachment {
		//	filename := filepath.Join(dir, v.Name+v.Remark)
		//	err = downloadFile(base+"/"+project.WordUrl, filename)
		//	if err != nil {
		//		beego.Debug(err)
		//		return "", err
		//	}
		//}
	}

	// 3.3 结项报告与附件
	if len(project.ImsProjectFinishReport) > 0 {
		finishReportDir := filepath.Join(dir, "结项报告")
		err = os.MkdirAll(finishReportDir, 0777)
		if err != nil {
			beego.Debug(err)
			return "", err
		}
		finishReport := project.ImsProjectFinishReport[0]
		err = downloadFile(base+"/"+finishReport.WordUrl, filepath.Join(finishReportDir, "结项报告.docx"))
		if err != nil {
			beego.Debug(err)
			return "", err
		}
		for _, v := range finishReport.ImsProjectFinishAttach {
			filename := filepath.Join(finishReportDir, v.Name)
			err = downloadFile(base+"/"+v.Url, filename)
			if err != nil {
				beego.Debug(err)
				return "", err
			}
		}
	}

	// 4. 压缩
	archiveName := filepath.Join("tmp", project.Creater+fmt.Sprint(time.Now().Unix())+".zip")
	err = archivePackage([]string{dir}, archiveName)
	defer os.RemoveAll(archiveName)
	// 5. 上传
	file, err := os.Open(archiveName)
	defer file.Close()
	if err != nil {
		beego.Debug(err)
		return "", err
	}
	fid, _, err = weed.Upload(archiveName, "", file)
	if err != nil {
		beego.Debug(err)
		return "", err
	}
	return
}

func makeTmpDir() (dir string, err error) {
	dir, err = ioutil.TempDir("tmp", "ims-")
	return
}

func downloadFile(url, dist string) error {
	client := http.DefaultClient
	client.Timeout = time.Second * 5 //设置超时时间
	resp, err := client.Get(url)
	if err != nil {
		beego.Debug(err)
		return err
	}
	raw := resp.Body
	defer raw.Close()

	file, err := os.Create(dist)
	if err != nil {
		beego.Debug(err)
		return err
	}
	defer file.Close()

	buf := make([]byte, 8)
	_, err = io.CopyBuffer(file, raw, buf)
	if err != nil {
		beego.Debug(err)
		return err
	}
	return nil
}

// archivePackage archive dir
func archivePackage(source []string, dist string) error {
	z := archiver.Zip{
		CompressionLevel:       flate.DefaultCompression,
		MkdirAll:               true,
		SelectiveCompression:   true,
		ContinueOnError:        false,
		OverwriteExisting:      false,
		ImplicitTopLevelFolder: false,
	}
	return z.Archive(source, dist)
}

func GetZipUrl(projectId string) (string, error) {
	project, err := GetImsProjectById(projectId)
	if err != nil {
		beego.Debug(err)
		return "", err
	}
	//if project.Remark != "" {
	//	return project.Remark, nil
	//} else {
	//	fid, err := generateZip(project)
	//	if err != nil {
	//		beego.Debug(err)
	//		return "", err
	//	}
	//	project.Remark = fid
	//	err = UpdateImsProjectById(project)
	//	if err != nil {
	//		beego.Debug(err)
	//		return "", err
	//	}
	//	return fid, nil
	//}
	fid, err := generateZip(project)
	if err != nil {
		beego.Debug(err)
		return "", err
	}
	project.Remark = fid
	err = UpdateImsProjectById(project)
	if err != nil {
		beego.Debug(err)
		return "", err
	}
	return fid, nil
}

func QueryProjectByIdList(idlist []string) ([]ImsProject, error) {
	o := orm.NewOrm()
	var list []ImsProject
	_, err := o.QueryTable(new(ImsProject)).Filter("id__in", idlist).RelatedSel().All(&list)
	return list, err
}

var sheet = "Sheet1"
var StartRow = 2
var Cells = []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S"}

func appendData2Xlsx(data []ImsProject) (string, error) {
	// 打开模板
	f, err := excelize.OpenFile("template/template.xlsx")
	if err != nil {
		fmt.Println(err)
		return "", err
	}
	// 填充数据
	for k, v := range data {
		row := getStartRow(k)
		cells := ArrayMap(makeCellID, row, Cells)
		fmt.Println(cells)
		f.SetCellInt(sheet, cells[0], v.Ctime.Year())
		f.SetCellStr(sheet, cells[1], "甘肃省")
		f.SetCellInt(sheet, cells[2], 10741)
		f.SetCellStr(sheet, cells[3], "兰州财经大学")
		f.SetCellValue(sheet, cells[4], "")
		f.SetCellValue(sheet, cells[5], v.Name)
		f.SetCellStr(sheet, cells[6], libs.GetImsProjectType(v.ProjectType))
		f.SetCellStr(sheet, cells[7], v.Creater)
		f.SetCellStr(sheet, cells[8], "学号")
		f.SetCellStr(sheet, cells[9], "其他成员信息")
		f.SetCellStr(sheet, cells[10], "指导教师姓名")
		f.SetCellStr(sheet, cells[11], "指导教师职称")
		f.SetCellValue(sheet, cells[12], "财政拨款(元)")
		f.SetCellValue(sheet, cells[13], "校拨(元)")
		f.SetCellValue(sheet, cells[14], v.Budget)
		f.SetCellValue(sheet, cells[15], v.SubjectId)
		f.SetCellStr(sheet, cells[16], v.Desc)
		f.SetCellStr(sheet, cells[17], v.ProvinceNo)
		f.SetCellStr(sheet, cells[18], v.No)
	}
	err = f.SaveAs("export.xlsx")

	return "", err
}

func getStartRow(index int) string {
	return fmt.Sprint(StartRow + index)
}

func makeCellID(row, cell string) string {
	var buffer bytes.Buffer
	buffer.WriteString(cell)
	buffer.WriteString(row)
	return buffer.String()
}

func ArrayMap(mapping func(string, string) string, row string, cols []string) []string {
	array := make([]string, 0)
	for _, c := range cols {
		r := mapping(row, c)
		array = append(array, r)
	}
	return array
}

func ExportXlsx(idlist []string) {
	list, err := QueryProjectByIdList(idlist)
	if err != nil {

	}
	appendData2Xlsx(list)
}
